package com.example.recyclerviewdemo;

import java.util.List;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {

    private LayoutInflater inflater;
    private List<User> userList;

    public UserAdapter(Context context, List<User> userList) {
        inflater = LayoutInflater.from(context);
        this.userList = userList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.activity_main_item, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        User user = userList.get(position);
        holder.tvTitle.setText(user.getName());
        holder.tvContent.setText(user.getEmail());
    }

    @Override
    public int getItemCount() {
        return userList == null ? 0 : userList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tvTitle;
        public TextView tvContent;

        public ViewHolder(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.main_item_tv_title);
            tvContent = (TextView) itemView.findViewById(R.id.main_item_tv_content);

            itemView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View view) {
                    User user = userList.remove(getPosition());
                    //UserAdapter.this.notifyItemRemoved(getPosition());
                    userList.add(user);
                    //UserAdapter.this.notifyItemInserted(userList.size() - 1);
                    UserAdapter.this.notifyItemMoved(getPosition(), userList.size() - 1);
                }

            });

        }

    }

}
